package com.usc.csci588.chaltrojan.location.map;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.usc.csci588.chaltrojan.SetDestinationMapActivity;
import com.usc.csci588.chaltrojan.login.Constants;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class CTItemizedOverlay2 extends CTItemizedOverlay {

	double latLong[];

	
	public static String getAddressString(Address addr){
		

		
		StringBuilder sb = new StringBuilder("");
		if (addr == null) return "";
		int maxAddrLineIdx = addr.getMaxAddressLineIndex();
		
		if (maxAddrLineIdx > 0){
			for(int i=0; i<maxAddrLineIdx; i++){
				sb.append(addr.getAddressLine(i)+", ");
			}
			int maxIdx = sb.length();
			sb.delete(maxIdx-2, maxIdx-1);
			return sb.toString();
		}
		
		if (addr.getFeatureName().trim() != ""){
			sb.append(addr.getFeatureName().trim() + ", ");
		}

		if (addr.getThoroughfare().trim() != ""){
			sb.append(addr.getThoroughfare().trim() + ", ");
		}

		if (addr.getLocality().trim() != ""){
			sb.append(addr.getLocality().trim() + ", ");
		}

		if (addr.getAdminArea().trim() != ""){
			sb.append(addr.getAdminArea().trim() );
		}

		sb.append(addr.getFeatureName() + ", "+addr.getThoroughfare()+ ", " + addr.getLocality()+ ", " + addr.getAdminArea());
		
		return sb.toString();
		
	}
	
	public CTItemizedOverlay2(Drawable defaultMarker) {
		super(defaultMarker);
		// TODO Auto-generated constructor stub
	}

	public CTItemizedOverlay2(Drawable defaultMarker, Context context) {
		super(defaultMarker, context);
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public boolean onTap(GeoPoint p, MapView map){
		Log.d("maps", "I am inside onTap function with point p and map m.. The tapped value is to be set destination");
		
		if (isPinch){
			return false;
		}
		
		///*
		final double latDest =  Constants.round(p.getLatitudeE6() * 1E-6 );
		final double longDest = Constants.round(p.getLongitudeE6() * 1E-6 );
		latLong = new double[] {latDest, longDest} ;
		Log.d("maps","latLong[] is "+latLong[0]+" ; "+latLong[1] );
		
		
//		String address = null;
//		
//		Geocoder geoCoder = new Geocoder(mContext);
//		try {
//			List<Address> addr = geoCoder.getFromLocation(latDest, longDest, 1);
//			//address = addr.get(0).getLocality()  + ", "+ addr.get(0).getAdminArea() + " ";
//			address = getAddressString(addr.get(0));
//			Log.d("maps","Address was set as..."+address);
//			//address = addr.get(0).getLocality() + addr.get(0).getFeatureName() + addr.get(0).getAdminArea() + addr.get(0);
//		} catch (IOException e) {
//			Log.d("maps", e.getMessage() );
//			
//		}		
//		
//		detailsFound(address);
		
		GetLocationTask gtask = new GetLocationTask(latDest, longDest);
		try {
			gtask.execute().get();
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (ExecutionException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
//		String address = null;
//		
//		Geocoder geoCoder = new Geocoder(mContext);
//		try {
//			List<Address> addr = geoCoder.getFromLocation(latDest, longDest, 1);
//			//address = addr.get(0).getLocality()  + ", "+ addr.get(0).getAdminArea() + " ";
//			address = getAddressString(addr.get(0));
//			Log.d("maps","Address was set as..."+address);
//			//address = addr.get(0).getLocality() + addr.get(0).getFeatureName() + addr.get(0).getAdminArea() + addr.get(0);
//		} catch (IOException e) {
//			//e.printStackTrace();
//			
//		}
//		
//		if (address == null){
//			address = "";
//		}
//		
//		final String loc_addr = address.toString();
//        AlertDialog.Builder adb = new AlertDialog.Builder(mContext);
//        adb.setTitle("Chal, Trojan!");
//        if (address == ""){
//        	adb.setMessage("Are you sure you want to go to "+latDest+","+longDest+"?");
//        } else {
//        	adb.setMessage("Are you sure you want to go to "+address+"?");
//        }
//        adb.setPositiveButton("Yes",
//        	new DialogInterface.OnClickListener(){
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					//We have to send this to intent
//					Intent i = new Intent();
//					Bundle destInfo = new Bundle();
//					destInfo.putDoubleArray("Lat_Long",latLong );
//					destInfo.putString("Address", loc_addr);
//					i.putExtras(destInfo);
//					
//					((Activity) mContext).setResult(SetDestinationMapActivity.DEST_FINAL,i);					
//					((Activity) mContext).finish();
//				}
//
//        	}
//        );
//        adb.setNegativeButton("Cancel", null);
//        adb.show();
//
		return true;
	}
	
	public void detailsFound(String address) {
		if (address == null){
			address = "";
		}
		
		final String loc_addr = address.toString();
        AlertDialog.Builder adb = new AlertDialog.Builder(mContext);
        adb.setTitle("Chal, Trojan!");
        if (address == ""){
        	adb.setMessage("Are you sure you want to go here?");
        } else {
        	adb.setMessage("Are you sure you want to go to "+address+"?");
        }
        adb.setPositiveButton("Yes",
        	new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					//We have to send this to intent
					Intent i = new Intent();
					//Bundle destInfo = new Bundle();
					//i.putExtras(destInfo);
					//i.putExtra("Dest_Info", destInfo);

					i.putExtra(Constants.Lat_Lng,latLong );
					i.putExtra(Constants.AddrSting, loc_addr);
					
					
					((Activity) mContext).setResult(SetDestinationMapActivity.DEST_FINAL,i);					
					((Activity) mContext).finish();
				}

        	}
        );
        adb.setNegativeButton("Cancel", null);
        adb.show();
		
		
	}

	
	private class GetLocationTask extends AsyncTask<Void, Void, Void> {
		String address;
		double lat;
		double lng;
		Address[] addrs;
		ProgressDialog pd;

		public GetLocationTask(double lat, double lng) {
			this.lat = lat;
			this.lng = lng;
			pd =  new ProgressDialog(CTItemizedOverlay2.this.mContext);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pd = ProgressDialog.show(CTItemizedOverlay2.this.mContext, "Selecting Destination..", "Fetching information...");
		}

		@Override
		protected Void doInBackground(Void... params) {
			getFromLocation(this.lat, this.lng);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			pd.dismiss();
			//generateString();
			//now we have to update UI:
			detailsFound(address);
			//detailsFound(generateString());

		}

		private String generateString(){
			if (addrs[0] == null) address = "";
			address = getAddressString(addrs[0]);
			return address;
		}


		private void getFromLocation(double lat, double lon) {

			String urlStr = "http://maps.google.com/maps/geo?q=" + lat + "," + lon + "&output=json&sensor=true";
			Log.d("maps","query is --> "+urlStr.toString());
			Address addr = null;
			String response = "";
			HttpClient client = new DefaultHttpClient();

			Log.d("ReverseGeocode", urlStr);
			try {
				HttpResponse hr = client.execute(new HttpGet(urlStr));
				HttpEntity entity = hr.getEntity();

				BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));

				String buff = null;
				while ((buff = br.readLine()) != null)
					response += buff;
			} catch (IOException e) {
				e.printStackTrace();
			}

			JSONArray responseArray = null;
			try {
				JSONObject jsonObject = new JSONObject(response);
				responseArray = jsonObject.getJSONArray("Placemark");
			} catch (JSONException e) {
				return;
			}

			Log.d("ReverseGeocode", "" + responseArray.length() + " result(s)");

			Address addy = new Address(Locale.getDefault());

			try {
				JSONObject jsl = responseArray.getJSONObject(0);

				String addressLine = jsl.getString("address");

//				if(addressLine.contains(",")) {
//					addressLine = addressLine.split(",")[0];
//					
//				}
				
				address = addressLine;

//				addy.setAddressLine(0, addressLine);
//
////				jsl = jsl.getJSONObject("AddressDetails").getJSONObject("Country");
////				addy.setCountryName(jsl.getString("CountryName"));
////				addy.setCountryCode(jsl.getString("CountryNameCode"));
//
//				jsl = jsl.getJSONObject("AddressLine");
//				addy.setAddressLine(getLastFocusedIndex(), jsl.getString("AddressLine"));
//				
//				jsl = jsl.getJSONObject("AdministrativeArea");
//				addy.setAdminArea(jsl.getString("AdministrativeAreaName"));
//
//				jsl = jsl.getJSONObject("SubAdministrativeArea");
//				addy.setSubAdminArea(jsl.getString("SubAdministrativeAreaName"));
//
//				jsl = jsl.getJSONObject("Locality");
//				addy.setLocality(jsl.getString("LocalityName"));
//
//				addy.setPostalCode(jsl.getJSONObject("PostalCode").getString("PostalCodeNumber"));
//				addy.setThoroughfare(jsl.getJSONObject("Thoroughfare").getString("ThoroughfareName"));

			} catch (JSONException e) {
				e.printStackTrace();
				address = "";
			}

//			addr = addy;
//
//			addrs[0] = addy;


			return ;
		}


	}

}
